package edu.thu.studio.ormdesigner.outline.action;

import java.util.List;

import org.eclipse.gef.EditPart;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.ui.parts.TreeViewer;
import org.eclipse.jface.action.Action;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Event;

import edu.thu.studio.ormdesigner.model.ORMModel;
import edu.thu.studio.ormdesigner.util.Utils;

public abstract class AbstractOutlineAction extends Action {
    
    private TreeViewer treeViewer;
    
    public AbstractOutlineAction(String id, String text, TreeViewer treeViewer) {
        this(id, text, SWT.NONE, treeViewer);
    }
    
    public AbstractOutlineAction(String id, String text, int style, TreeViewer treeViewer) {
        super(text, style);
        this.setId(id);
        this.treeViewer = treeViewer;
    }
    
    /**
     * {@inheritDoc}
     */
    @Override
    public final void runWithEvent(Event event) {
        try {
            execute(event);
        } catch (Exception e) {
            Utils.showExceptionDialog(e);
        }
    }
    
    protected void execute(Command command) {
        this.treeViewer.getEditDomain().getCommandStack().execute(command);
    }
    
    protected ORMModel getORMModel() {
        EditPart editPart = treeViewer.getContents();
        ORMModel model = (ORMModel) editPart.getModel();
        
        return model;
    }
    
    /**
     * 获取当前选择的第一个数据对象
     * 
     * @return
     */
    public Object getSelectedModel() {
        @SuppressWarnings("rawtypes")
        List selectedEditParts = treeViewer.getSelectedEditParts();
        if (!selectedEditParts.isEmpty()) {
            return ((EditPart) treeViewer.getSelectedEditParts().get(0)).getModel();
        }
        return null;
    }
    
    protected TreeViewer getTreeViewer() {
        return treeViewer;
    }
    
    abstract public void execute(Event event) throws Exception;
    
}
